<template>
  <el-dialog
    @close="closeDialog"
    v-model="dialogVisible"
    :title="title"
    width="50%"
  >
    <el-form
      ref="ruleFormRef"
      :model="formData"
      :rules="rules"
      label-width="120px"
      class="demo-ruleForm"
      status-icon
    >
      <el-row v-if="parentSelectShow">
        <el-col :span="12">
          <el-form-item label="上级菜单" prop="parentId">
            <el-select
              v-model="formData.parentId"
              placeholder="Select"
              style="width: 100%"
            >
              <el-option
                v-for="{ value, label } in menuOption"
                :key="value"
                :label="label"
                :value="value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="名称" prop="menuName">
            <el-input v-model="formData.menuName" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="CODE" prop="menuCode">
            <el-input v-model="formData.menuCode" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="菜单图标" prop="menuIcon">
            <el-input v-model="formData.menuIcon" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="路由地址" prop="menuUrl">
            <el-input v-model="formData.menuUrl" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="组件路径" prop="component">
            <el-input v-model="formData.component" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="排序" prop="sort">
            <el-input-number v-model="formData.sort" :min="0" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="state">
            <el-switch
              :active-value="1"
              :inactive-value="2"
              v-model="formData.state"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="footer">
      <el-button
        @click="submitForm(ruleFormRef)"
        type="primary"
        :loading="submitLoading"
      >
        保存
      </el-button>
      <el-button @click="closeDialog">取消</el-button>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, reactive, ref, watch } from "vue";
import { ElMessage, FormInstance, FormRules } from "element-plus";
import { saveMenu, updateMenu } from "@/api/system.ts";
import { ApiResult } from "@/util/request";

interface IDate {
  id: string;
  parentId: string;
  component: string;
  menuCode: string;
  menuIcon: string;
  menuUrl: string;
  menuName: string;
  state: number | string;
  sort: number | string;
}

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  data: {
    type: Object,
    default: () => {},
  },
  parentMenuOption: {
    type: Array,
    default: () => [],
  },
});

const emit = defineEmits(["update:visible", "update:data", "submit"]);

const ruleFormRef = ref();
const submitLoading = ref<boolean>(false);

const formData = reactive<IDate>({
  id: "",
  parentId: "",
  component: "",
  menuName: "",
  menuCode: "",
  menuIcon: "",
  menuUrl: "",
  state: 1,
  sort: 1,
});

//TODO 做成动态
const rules = reactive<FormRules<IDate>>({
  component: [{ required: true, message: "请输入组件路径", trigger: "blur" }],
  menuName: [{ required: true, message: "请输入菜单名称", trigger: "blur" }],
  menuCode: [{ required: true, message: "请输入菜单编码", trigger: "blur" }],
  menuUrl: [{ required: true, message: "请输入路由地址", trigger: "blur" }],
  sort: [{ required: true, message: "请输入菜单图片", trigger: "blur" }],
  parentId: [{ required: true, message: "父级菜单", trigger: "change" }],
});

const dialogVisible = computed({
  get() {
    return props.visible;
  },

  set(visible: boolean) {
    emit("update:visible", visible);
  },
});

//TODO 做成动态
const title = computed(() => {
  return formData?.id ? "编辑菜单" : "新增菜单";
});

const parentSelectShow = computed(() => {
  return !["0", ""].includes(formData?.parentId);
});

const menuOption = computed(() => {
  return (
    props.parentMenuOption?.map((menu: any) => {
      return {
        value: menu?.id,
        label: menu?.menuName,
      };
    }) || []
  );
});

function closeDialog() {
  resetForm(ruleFormRef.value);
  emit("update:visible", false);
  emit("update:data", null);
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    let result: ApiResult<any>;
    if (valid) {
      submitLoading.value = true;
      if (formData?.id) {
        result = await updateMenu(formData);
      } else {
        result = await saveMenu(formData);
      }
      const { success, msg } = result;
      submitLoading.value = false;
      if (!success) {
        ElMessage.error(msg);
        return;
      }
      closeDialog();
      emit("submit");
    } else {
      console.log("error submit!", fields);
    }
  });
};

watch(dialogVisible, (visible) => {
  Object.keys(formData).forEach((key: any) => {
    formData[key as keyof IDate] = visible ? props.data?.[key] || "" : "";
  });
  formData.state = formData.state ? Number(formData.state) : 1;
  formData.sort = Number(formData.sort);
  formData.component = formData.component
    ? formData.component
    : "layout/layout";
});
</script>

<style scoped lang="scss">
.footer {
  width: 100%;
  text-align: center;
  margin-top: 50px;
}
</style>
